package nighttest.day03;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 将当前目录下的所有文件都复制一份，复制的文件命名为:原文件名_cp.后缀
 * 比如原文件为:test.dat
 * 复制后的文件为:test_cp.dat
 * @author Xiloer
 */
public class test3_3 {
    public static void main(String[] args) throws IOException {
        File dir = new File(".");
        if(dir.isDirectory()) {
            //File[] subs = dir.listFiles();
            FileFilter filter = (file) ->file.isFile();//判断file对象是否是一个文件
            File[] subs = dir.listFiles(filter);
            System.out.println(subs.length);
            //遍历所有获取到的文件并进行复制
            for (int i = 0; i < subs.length; i++) {
                String name = subs[i].getName();
                RandomAccessFile raf = new RandomAccessFile(subs[i], "r");
                /*
                StringBuilder sname = new StringBuilder(name);
                int a = sname.lastIndexOf(".");
                sname.insert(a,"_cp");
                String copyname = sname.toString();
                 */
                int index = name.lastIndexOf(".");
                String name1 = name.substring(0,index); //提取点前面的数据
                String name2 = name.substring(index);//提取点及点后面的数据
                String copyname = name1 + "_cp" + name2;
                RandomAccessFile copy = new RandomAccessFile(copyname, "rw");
                int len;//记录每次块读数据后，实际读取到的字节数
                byte[] data = new byte[1024 * 10];//10kb
                long start = System.currentTimeMillis();
                while ((len = raf.read(data)) != -1) {//读10kb
                    copy.write(data,0,len);//读了多少字节，就一次写多少字节
                }
                long end = System.currentTimeMillis();
                System.out.println("复制完毕！耗时"+(end-start)+"ms");
                raf.close();
                copy.close();

            }
        }

    }
}
